package easy;

import java.util.Arrays;

/**
 * @author wangtianqi
 *
 * 724. 寻找数组的中心下标
 */
public class pivotIndex {
    public static void main(String[] args) {
        int[] test = {-1,-1,-1,-1,-1,0};
        System.out.println(myCode(test));
    }

    /**
     * 错误
     * @param nums
     * @return
     */
    public static int myCode(int[] nums) {
        int p1 = 0;
        int p2 = nums.length - 1;
        int sum1 = nums[p1];
        int sum2 = nums[p2];

        while (p1 <= p2) {
            if (sum1 < sum2) {
                if (p1 < p2){
                    p1++;
                    sum1 += nums[p1];
                }
            } else if (sum2 < sum1) {
                if (p1 < p2){
                    p2--;
                    sum2 += nums[p2];
                }
            } else {
                if (p1 < p2 && p2 - p1 == 2) {
                    p1++;
                    return p1;
                } else if (p1 ==p2 && sum1 == nums[p1]) {
                    return p1;
                } else {
                    p1++;
                    p2--;
                    sum1 += nums[p1];
                    sum2 += nums[p2];
                }
            }
        }
        return -1;
    }

    /**
     * 答案
     * @return
     */
    public static int myCode2(int[] nums) {
        int total = Arrays.stream(nums).sum();
        int sum = 0;
        for (int i = 0; i < nums.length; ++i) {
            if (2 * sum + nums[i] == total) {
                return i;
            }
            sum += nums[i];
        }
        return -1;
    }
}
